﻿if (typeof Axis == "undefined") Axis = {};
if (typeof Axis.Admin == "undefined") Axis.Admin = {};
Axis.Admin.ProductImage = {
    Init: function () {
        var thisObj = this;
        thisObj.Grid.Init();
        thisObj.EventClick();
               $("button").button();
    },
    DropdownChecklist: {
        Instance: null,
        Init: function () {
            $("#FormEdit,#FormFilter").show();
            var thisObj = this;
            thisObj.Instance = new CDropDownCheckList({ width: 200, maxDropHeight: 110, firstItemChecksAll: true });
            thisObj.Instance.Init("#FormEdit select[multiple]");
            thisObj.Instance.Init("#FormFilter select[multiple]");
            $("#FormEdit,#FormFilter").hide();
        },
        Clear: function () {
            var thisObj = this;
            $("#FormEdit select[multiple]").find("option").removeAttr("selected");
            thisObj.Refresh();
        },
        Refresh: function () {
            var thisObj = this;
            if (thisObj.Instance) {
                thisObj.Instance.Refresh();
            }
        }
    },
    Grid: {
        ID: "#GridContents",
        PagesID: "#GridPages",
        Init: function () {
            var thisObj = this;
            var options = {
                url: '../Home/Service/GetImageProduct.ashx?Action=GET&Context=Backend&ProductID='+ProductID,
                datatype: "json",
                 multiselect:true,
                colNames: [
                    'ID', 'ProducID', 'Thumbnail', 'Thumbnail','LargeImage','LargeImage',
                    '','','Trạng thái','Xử lý'
                        ],
                colModel: [
                    { name: 'ID', index: 'ID', width: 50, frozen: true, hidden: true, hidedlg: true },
                    { name: 'ProducID', index: 'ProducID', width: 100, frozen: true, hidedlg: true , hidden: true},
                     { name: 'Thumbnail', index: 'Title', width: 1, hidden: true,frozen: true},
                    { name: 'ThumbnailString', index: 'Title', width: 250, frozen: true, align:'center'},
                    { name: 'LargeImage', index: 'Title', width: 1, hidden: true,frozen: true},
                     { name: 'LargeImageString', index: 'Title', width: 250, frozen: true,align:'center'},
                    { name: 'Status', index: 'Title', width: 55, frozen: true, hidedlg: true,hidden: true},
                    
                    { name: 'ZOrder', index: 'Title', width: 55, frozen: true, hidedlg: true,hidden: true},
                    { name: 'StatusString', index: 'Title', width: 70, frozen: true, align:'center'},
                    { name: 'Action', index: 'Action', width: 55, align: 'center' }
                     
                
                ],
               
                gridComplete: function () {

                },
                onCellSelect: function (rowid, iCol, cellcontent, e) {

                },
                onSelectRow: function (rowid, status, e) {

                },
                ondblClickRow: function (rowid, iRow, iCol, e) {

                },
                afterInsertRow: function (rowid, aData, addData) {
                    var action = $.string.Format("<img class='imgAction' src='../../Images/16x16/edit.png' onclick=\"ShowEdit('{0}')\"/>", rowid);
                    $(thisObj.ID).jqGrid('setCell', rowid, 'Action', action);
                    var iconStatus='s_enable.png';
                      if(aData.Status=='0')
                     iconStatus='s_visible.png';
                     var StatusString= $.string.Format("<img class='imgAction' src='../../Images/16x16/{0}' onclick=\"ActionStatus('{1}',{2},{3})\"/>", iconStatus,rowid,aData.Status,aData.ProductID);
                     $(thisObj.ID).jqGrid('setCell', rowid, 'StatusString', StatusString );
                        var LargeImageString= $.string.Format("<img class='imgView' src='{0}' />", aData.LargeImage);
                     $(thisObj.ID).jqGrid('setCell', rowid, 'LargeImageString', LargeImageString );
                        var ThumbnailString= $.string.Format("<img class='imgView' src='{0}' />", aData.Thumbnail);
                     $(thisObj.ID).jqGrid('setCell', rowid, 'ThumbnailString', ThumbnailString );
                },
                multiselect: true,
                height: 'auto',
                rownumbers: true,
                autowidth: true,
                //forceFit: true,
                shrinkToFit: false,
                rowNum: 20,
                pager: thisObj.PagesID
            };
            thisObj.GridObj = new CGrid(options);
            thisObj.GridObj.Init(thisObj.ID);
            thisObj.GridObj.NavGrid();
            thisObj.GridObj.FrozenColumns();
        },
        Reload: function () {
            var thisObj = this;
            if (thisObj.GridObj)
                thisObj.GridObj.ReloadGrid();
        },
        SelectRow: function () {
            var thisObj = this;
            if (thisObj.GridObj) {
                return thisObj.GridObj.SelectRow();
            }
            return null;
        },
        SetNewUrl:function(url){
            var thisObj = this;
            thisObj.GridObj.setGridParam({ url: url });
            thisObj.Reload();
            
        },
        GetRowData:function(id){
            var thisObj = this;
        return $(thisObj.ID).jqGrid('getRowData',id);
        }
    },
    DialogEdit: {
        ID: "#FormEdit",
        Dialog: null,
        Init: function (action, opts) {
            var thisObj = this;
            thisObj.ClearForm();
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
            else {
                thisObj.Dialog = new CDialog({
                    title: "Thêm Loại Sản Phẩm",
                    width: 400,
                    position: {
                        my: 'top',
                        at: 'top'
                    },
                    open: function () {
                      
                    }
                });
                thisObj.Dialog.Init(thisObj.ID);
            }
            var buttonText = "";
            switch (action) {
                case "INSERT":
                    thisObj.Dialog.SetTitle("Thêm hình ảnh");
                    $(thisObj.ID).find("[data-role='INSERT']").show();
                    $(thisObj.ID).find("#txtLoginName").focus();
                    buttonText = "Thêm";
                    $("#txtStatus").attr('checked', 'checked');
                    break;
                case "UPDATE":
                    thisObj.Dialog.SetTitle("Sửa: " + opts.Code);
                    $.each(opts, function (key, value) {
                    switch(key){                       
                        case 'Status':
                         if(value=="1") $(thisObj.ID).find("[data-field=" + key + "]").attr('checked','checked')
                         else 
                          $(thisObj.ID).find("[data-field=" + key + "]").removeAttr('checked','checked')
                        break;
                       
                        default:
                         $(thisObj.ID).find("[data-field=" + key + "]").val(value);
                    }

                    });

                    buttonText = "Hiệu chỉnh";
                    break;
            }
            var buttons = [
                        {
                            text: buttonText,
                            click: function (e) {
                                Axis.Admin.ProductImage.Update(action, opts);
                                thisObj.Close();
                            }
                        },
                        {
                            text: "Đóng",
                            click: function (e) {
                                thisObj.Close();
                            }
                        }

            ];
            $(thisObj.ID).dialog('option', 'buttons', buttons);
        },
        Open: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
        },
        Close: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Close();
            }
        },
        LoadNews: function (opt) {

        },
        ClearForm: function () {
            $("#FormEdit").find("[data-field]").each(function () {
                var $this = $(this);
                $this.val("");
                if ($this.is("select")) {
                    var value = $this.find("option[Default-Value='1']").attr("value");
                    $this.val(value);
                }

            });
            $("#FormEdit").find("[data-role='INSERT']").hide();
//            if (CKEDITOR && CKEDITOR.instances["Content_VI"])
//                CKEDITOR.instances["Content_VI"].setData('');
//            if (CKEDITOR && CKEDITOR.instances["Content_EN"])
//                CKEDITOR.instances["Content_EN"].setData('');
        }
    },
    Update: function (type, opts) {
        var thisObj = this;
        var data = {};
        switch (type) {
           case "INSERT":
            case "UPDATE":
                $("#FormEdit").find("[data-field]").each(function () {
                    var $this = $(this);
                    if ($this.attr("data-field")) {
                        var key = $this.attr("data-field");
                        var value = $this.val();
                        if ($this.attr('type') == 'checkbox') {
                            if ($this.is(':checked'))
                                value = 1;
                        }
                                          
                        data[key] = value;
                    }
                });
                break;
            case "DELETE":
            case "ACTIVE":
            case "DEACTIVE":
                data.ID = opts.ID;
                break;  
                case "DELETEMULTI":
                data.IDs = opts.IDs;
                break;             
        }
        data.ProductID = ProductID;
        data.Action = type;
        $.Ajax({
            url: '../Home/Service/GetImageProduct.ashx',
            type: 'POST',
            data: data,
            success: function (data, textStatus, jqXHR) {
                if (data) {
                    data = eval("(" + data + ")");
                    if (data.IsSuccessfull) {
                        thisObj.Grid.Reload();
                    }
                }
            },
            beforeSend: function (jqXHR, settings) {
            },
            error: function (jqXHR, textStatus, errorThrown) {
            },
            complete: function (XMLHttpRequest, textStatus) {
            }
        });
    },
    Filter: function (type, opts) {
        var thisObj = this;  
        var data={};     
                $("#FormFilter").find("[data-field]").each(function () {
                    var $this = $(this);
                    if ($this.attr("data-field")) {
                        var key = $this.attr("data-field");
                        var value = $this.val();
                        if ($this.attr('type') == 'checkbox') {
                            if ($this.is(':checked'))
                                value = 1;
                        }

                        if ($this.attr("role") == "datepicker") {
                            value = $.CFormat.FormatDate(value, "yyyy/MM/dd HH:mm", "vi-VN", "en-US");
                        }
                        if (key == "Tags") {
                            if (value && $.isArray(value)) {
                                value = value.join(",");
                            }
                        }
                        data[key] = value;
                    }
                });
             var   url='Service/GetNewsList.ashx?Action=GET&Context=Backend'  ;
        for(var key in data){
            var attrName = key;
            var attrValue = data[key];
            if(attrValue==null)
                attrValue = "";
            url+= $.string.Format("&{0}={1}",attrName,attrValue);
        }
        thisObj.Grid.SetNewUrl(url);
                 
    },
    DialogFilter: {
        ID: "#FormFilter",
        Dialog: null,
        Init: function (action, opts) {
            var thisObj = this;
            thisObj.ClearForm();
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
            else {
                thisObj.Dialog = new CDialog({
                    title: "Tìm hình ảnh sản phẩm",
                    width: 300,
                    position: {
                        my: 'top',
                        at: 'top'
                    },
                    open: function () {
                       }
                });
                thisObj.Dialog.Init(thisObj.ID);
            }
            var buttonText = "Tìm";
            
            var buttons = [
                        {
                            text: buttonText,
                            click: function (e) {
                                Axis.Admin.ProductImage.Filter(action, opts);
                                thisObj.Close();
                            }
                        },
                        {
                            text: "Đóng",
                            click: function (e) {
                                thisObj.Close();
                            }
                        }

            ];
            $(thisObj.ID).dialog('option', 'buttons', buttons);
        },
        Open: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
        },
        Close: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Close();
            }
        },
        
        ClearForm: function () {
            $("#FormFilter").find("[data-field]").each(function () {
                var $this = $(this);
                $this.val("");
                if ($this.is("select")) {
                    var value = $this.find("option[Default-Value='1']").attr("value");
                    $this.val(value);
                }

            });
            $("#FormFilter").find("[data-role='INSERT']").hide();

            Axis.Admin.ProductImage.DropdownChecklist.Clear();
        }
    },
    EventClick: function () {
        var thisObj = this;
        $("#btnSelectImg").click(function () {
            var finder = new CKFinder();
            finder.resourceType = 'Images';
            finder.startupPath = "Images:/ProductDetail/";
            finder.selectActionFunction = function (fileUrl) {
                $('#txtLargeImage').val(fileUrl);
            };
            finder.popup();
        });
         $("#btnSelectThumbnail").click(function () {
            var finder = new CKFinder();
            finder.resourceType = 'Images';
            finder.startupPath = "Images:/ProductDetail/";
            finder.selectActionFunction = function (fileUrl) {
                $('#txtThumbnail').val(fileUrl);
            };
            finder.popup();
        });

        $("#imgUserAdd").click(function () {
            thisObj.DialogEdit.Init("INSERT");
        });
        $("#imgUserEdit").click(function () {
            var rowData = thisObj.Grid.SelectRow();
            if (rowData && rowData.ID)
                thisObj.DialogEdit.Init("UPDATE", rowData);
            else alert("Please Select Row");
        });
        $("#imgUserDel").click(function () {
        thisObj.DeleteNews();

        });
        $("#imgUserBack").click(function () {
           history.go(-1);
        });

    },
    DeleteNews: function (id) { 
    var thisObj=this;
      var rowData = thisObj.Grid.SelectRow();
      if(typeof id!='undefined'){
            rowData=thisObj.Grid.GetRowData(id);
            if (rowData && rowData.ID) {
                $.CAlert.Confirm({
                    Title: "Xóa hình ảnh sản phẩm",
                    Content: $.string.Format("Bạn có chắc muốn xóa hình ảnh sản phẩm: [{0}].", rowData.Title),
                }, function (isOK) {
                    if (isOK)
                        thisObj.Update("DELETE", rowData);
                });
            }
            else {
                $.CAlert.Alert({
                    Title: "Xóa hình ảnh sản phẩm",
                    Content: "Vui lòng chọn hình ảnh sản phẩm cần xóa.",
                });
            }
    }
    else{
     $.CAlert.Confirm({
                    Title: "Xóa hình ảnh sản phẩm",
                    Content: $.string.Format("Bạn có chắc muốn xóa hình ảnh sản phẩm đã chọn",''),
                }, function (isOK) {
                    if (isOK){
                   rowData.IDs= $(thisObj.Grid.ID).jqGrid('getGridParam','selarrrow').toString();
                        thisObj.Update("DELETEMULTI", rowData);
                        }
                });

        }
    }
};
$(function () {
    Axis.Admin.ProductImage.Init();
});
function ShowEdit(rowID) {
    var thisObj = Axis.Admin.ProductImage;
    var rowData = $(thisObj.Grid.ID).jqGrid('getRowData', rowID);
    if (rowData && rowData.ID)
        thisObj.DialogEdit.Init("UPDATE", rowData);
}
function DeleteNews(rowID) {
 Axis.Admin.ProductImage.DeleteNews(rowID);
}
function FormatGridDescription(cellvalue, options, rowObject) {
    if (cellvalue.indexOf("project_desc_panel") == -1) {
        return '<div class="project_desc_panel">' + cellvalue + '</div>';
    }
    else
        return cellvalue;

}
function ActionStatus(rowID,Status,ProductID){
var thisObj=Axis.Admin.ProductImage;
    var newStatus="Active";
    var action="DEACTIVE";
    Status=parseInt(Status);
    if(Status==1){
    newStatus="DeActive";
    action="ACTIVE";
    }
    if(Status==-1)
    return;
    var rowData={ID:rowID};
    if (rowData && rowData.ID) {
                $.CAlert.Confirm({
                    Title: "Cập nhật trạng thái hình ảnh sản phẩm",
                    Content: $.string.Format("Bạn có chắc muốn thay đôi trạng thái hình ảnh sản phẩm", newStatus),
                }, function (isOK) {
                    if (isOK)
                        thisObj.Update(action, rowData);
                });
            }
            else {
                $.CAlert.Alert({
                    Title: "Xóa hình ảnh sản phẩm",
                    Content: "Vui lòng chọn hình ảnh sản phẩm cần xóa.",
                });
            }


}